/**
 * 
 */
package com.blog.filter;

import java.util.HashSet;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import com.blog.core.http.HttpStatus;
import com.blog.exception.KittyException;
import com.blog.oauth2.JWTToken;
import com.blog.pojo.SysUser;
import com.blog.pojo.SysUserToken;
import com.blog.service.SysUserService;
import com.blog.service.SysUserTokenService;
import com.blog.util.JWTUtil;

/**
 * @author zyj
 *
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {
	
	@Autowired
	private SysUserTokenService sysUserTokenService;
	
	@Autowired
	private SysUserService sysUserService;
	
	//登录标识
	private static String LOGIN_SIGN = "token";
	
	/* 
	 * 检查用户名是否登录
	 * 检查header里面是否包含Authorization字段即可
	 */
	@Override
	protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
		HttpServletRequest req = (HttpServletRequest) request;
		String authorization = req.getHeader(LOGIN_SIGN);
		if(StringUtils.isNotBlank(authorization)) {
			SysUserToken userToken = sysUserTokenService.findByToken(authorization);
			SysUser user = sysUserService.get(userToken.getId());
			boolean flag = JWTUtil.verify(authorization, user.getName(), user.getPassword()); 
			return !flag;
		}
		return true;
	}
	
	/* 
	 * 
	 */
	@Override
	protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest req = (HttpServletRequest) request;
		String header = req.getHeader(LOGIN_SIGN);
		JWTToken token = new JWTToken(header);
		getSubject(request, response).login(token);
		return true;
	}
	
	@Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            try {
                executeLogin(request, response);
            } catch (Exception e) {
                throw new KittyException("登录权限不足！", e);
            }
        }

        return true;
    }
	
	/**
     * 对跨域提供支持
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("http://localhost:8080"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "token,Access-Control-Allow-Origin,Access-Control-Allow-   Methods,Access-Control-Max-Age,authorization");
        httpServletResponse.setHeader("Content-Type","application/json; charset=utf-8");
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.SC_OK);
            return false;
        }
        return super.preHandle(request, response);
    }
    
    private boolean verificationPassAnnotation(ServletRequest request, ServletResponse response, HttpServletRequest httpServletRequest, String authorization) throws Exception {
        for (String urlMethod: new HashSet<String>()) {
            String[] split = urlMethod.split(":--:");
            if(split[0].equals(httpServletRequest.getRequestURI())
                    && (split[1].equals(httpServletRequest.getMethod()) ||  split[1].equals("RequestMapping"))){
                //Constant.isPass=true;
//                if(ComUtil.isEmpty(authorization)){
//                    //如果当前url不需要认证，则注入当前登录用户时，给一个空的
//                    httpServletRequest.setAttribute("currentUser",new User());
//                    return true;
//                }else {
//                    super.preHandle(request, response);
//                }
            }
//            if(StringUtils.countMatches(urlMethod, "{")>0 &&
//                    StringUtils.countMatches(urlMethod, "/") == StringUtils.countMatches(split[0], "/")
//                    && (split[1].equals(httpServletRequest.getMethod()) ||  split[1].equals("RequestMapping"))){
//                if(isSameUrl(split[0],httpServletRequest.getRequestURI())){
//                    Constant.isPass=true;
//                    if(ComUtil.isEmpty(authorization)){
//                        httpServletRequest.setAttribute("currentUser",new User());
//                        return true;
//                    }else {
//                        super.preHandle(request, response);
//                    }
//                }
//            }
        }
        return false;
    }
    
    public static void main(String[] args) {
    	System.out.println(1);
    	for (String urlMethod: new HashSet<String>()) {
    		System.out.println(urlMethod);
            String[] split = urlMethod.split(":--:");
            System.out.println(split);
        }
	}

}
